<?php
namespace app\api\controller;

use app\common\model as M;

/**
 * 签到任务
 */
class Sign extends \app\api\ApiAuth
{
    public $model = '\app\common\model\SignRecords';

    /**
     * 用户本周签到记录
     */
    public function week_records()
    {
        $today = new \DateTime();
        $week_start = $today->modify('this week')->format('Y-m-d');
        $week_end   = $today->modify('+6 days')->format('Y-m-d');
        $days = [];
        while ( strtotime($week_start) <= strtotime($week_end) ) {
            $days[] = $week_start;
            $week_start = date('Y-m-d',strtotime( $week_start . ' +1 days' ));
        }

        // 当前是一年中的第几周
        $curWeekNumber = date('W');
        $sign_golds =  \think\Env::get('SYSTEM.SIGN_GOLDS');
        $records = [];
        $date_flag = 0;
        foreach ( $days as $day ) {
            $golds = $signed = 0;
            $day_show = $day;

            ## 过去及今天日期:取实际记录上已经存在的获得金币数
            if ( strtotime($day) <= strtotime(date('Y-m-d')) ) {
                // 过去
                $date_flag = 1;
                $golds = M\UserSignRecords::where(['sign_date' => $day,'uid' => $this->uid, 'week' => $curWeekNumber])->value('golds')+0;
                if ( $golds > 0 ) $signed = 1;

                // 今天
                if ( strtotime($day) == strtotime(date('Y-m-d')) ) {
                    $date_flag = 2;

                    ## 上一天是否签到
                    $last_day = date('Y-m-d',strtotime($day . ' -1 days'));
                    $week_persist = M\UserSignRecords::where(['sign_date' => $last_day,'uid' => $this->uid, 'week' => $curWeekNumber])->value('week_persist')+0;
                    if ( $week_persist > 0 ) {
                        $week_persist++;
                    }else{
                        $week_persist = 1;
                    }
                    $golds = M\SignConfig::where('week_persist',$week_persist)->value('gift_golds')+0;
                }
            }
            ## 未来
            else {
                $date_flag = 3;

                ## 以今天为起点。看今天有没有签到，如果有签到看连续签到几天，如果没有则连续天数为1
                $week_persist = M\UserSignRecords::where(['sign_date' => date('Y-m-d'),'uid' => $this->uid, 'week' => $curWeekNumber])->value('week_persist')+0;
                if ( !$week_persist ) $week_persist = 1;

                ## 跟今天间隔天数
                $furtureDay = new \DateTime($day);
                $today1 = new \DateTime(date('Y-m-d'));
                $interval = $today1->diff($furtureDay);
                $diffDays = $interval->format('%d');
                $persist = $week_persist + $diffDays;
                $golds = M\SignConfig::where('week_persist',$persist)->value('gift_golds')+0;
            }

            $records[] = [
                'date'     => $day,
                'date_text'=> date('m/d',strtotime($day)),
                'golds'    => $golds,
                'date_flag'=> $date_flag,
                'signed'   => $signed
            ];
        }
        $this->returnSuccess($records);
    }

    /**
     * 已连续签到天数
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function week_persist()
    {
        $curWeekNumber = date('W');
        $today = date('Y-m-d');
        $todaySign = M\UserSignRecords::where(['sign_date' => $today,'uid' => $this->uid, 'week' => $curWeekNumber])->find();
        $week_persist = 0;
        if( !empty($todaySign) ) {
            $week_persist = $todaySign->week_persist;
        }
        return $this->returnSuccess(['week_persist' => $week_persist]);
    }

    /**
     * 用户发起签到
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function record()
    {
        $today = date('Y-m-d');
        $curWeekNumber = date('W');

        ## 检查今天是否已经签到过
        $isSigned = M\UserSignRecords::where(['sign_date' => $today,'uid' => $this->uid, 'week' => $curWeekNumber])->count();
        if ( $isSigned ) return $this->returnFail('今天已经签过到啦~');

        M\UserSignRecords::startTrans();
        try {
            ## 01记录签到记录
            $lastDay = date('Y-m-d',strtotime('-1 days'));
            $lastSign = M\UserSignRecords::where(['sign_date' => $lastDay,'uid' => $this->uid, 'week' => $curWeekNumber])->find();
            $week_persist = 1;
            if( !empty($lastSign) ) {
                $week_persist = $lastSign->week_persist + 1;
            }
            $golds = M\SignConfig::where('week_persist',$week_persist)->value('gift_golds')+0;
            if ( !$golds ) $golds =  \think\Env::get('SYSTEM.SIGN_GOLDS');
            $res = M\UserSignRecords::create([
                'sign_date'     => $today,
                'uid'           => $this->uid,
                'week'          => $curWeekNumber,
                'week_persist'  => $week_persist,
                'golds'         => $golds
            ]);
            if ( $res === false ) throw new \Exception('签到失败【10001】');

            ## 02金币账单（含增加用户金币余额）
            $res = M\user\UserGoldsBill::add($amt = $golds , $stype = M\user\UserGoldsBill::STYPE_SIGN , $uid = $this->uid);
            if ( $res === false ) throw new \Exception('签到失败【10002】');

            M\UserSignRecords::commitTrans();
            return $this->returnSuccess(['week_persist' => $week_persist,'golds' => $golds]);
        } catch (\Exception $e) {
            M\UserSignRecords::rollbackTrans();
            return $this->returnFail($e->getMessage());
        }

        M\UserSignRecords::rollbackTrans();
        return $this->returnFail('签到失败，请稍后再试~');
    }
}//Class End